from   myapp    import app , myapp
import os
import tempfile
import unittest

exec(open(app.root_path + '/constants/app_constants.py'  ).read())
exec(open(app.root_path + '/constants/tests_constants.py').read())


class MyAppTestCase(unittest.TestCase):

  def setUp(self):
    # test client and db
    app.config[TESTING_KEY]         = True
    self.client                     = app.test_client()
    self.db_fd , app.config[DB_KEY] = tempfile.mkstemp()

    # test fixtures
    with app.app_context():
      myapp.init_db()
      myapp.insert_post(TEST_POST_1)
      myapp.insert_post(TEST_POST_2)


  def tearDown(self):
    os.close(self.db_fd)
    os.unlink(app.config[DB_KEY])


  #def test_setup(self):
    #with app.app_context():
      #db = myapp.get_db()
      #res = db.execute(FETCH_POSTS_SQL).fetchall()
      #print(res)
      #for row in res: print(row[0] + " " + row[1])
      #assert False


  def login(self , username , password):
    params = dict(username = username , password = password)

    return self.client.post(LOGIN_ROUTE , data = params , follow_redirects = True)


  def logout(self):
    return self.client.get(LOGOUT_ROUTE , follow_redirects = True)


  #def get_current_user(self):
    #with app.app_context():
      #user = getattr(g , 'user' , None)
    #return
    #if user is None:
      #with app.test_request_context('/?name=Peter'):
        #assert myapp.request.path == '/'
        #user = myapp.request.fetch_current_user_from_database()
        #g.user = user
    #return user


  #def get_sassion_val(self , a_key):
    #aapp = Flask(__name__)
    #with aapp.test_client() as c:
      #with c.session_transaction() as sess:
        #sess[a_key] = 'a value'
